#include "TcpSocketServer.h"
QMap<QString,TcpSocket*> TcpSocket::tcpTree;
void TcpSocketServer::response_handle(processObject p)
{
    processObject response=processObject();
    QString userid;
    QString content;
    response=p;
    userid=QString::fromStdString(response.getUser());
    content=QString::fromStdString(response.getResult());
    if(TcpSocket::tcpTree.contains(userid))
    {
        TcpSocket *socket=TcpSocket::tcpTree[userid];
        socket->write(content.toUtf8());
        socket->flush();
    }
    else
    {
        qDebug()<<"tcp map中不含这个键值对";
    }
    close();

}

TcpSocketServer::TcpSocketServer(){}


void TcpSocketServer::incomingConnection(qintptr handle)
{
    TcpSocket *oTcpSocket=new TcpSocket();
    oTcpSocket->setSocketDescriptor(handle);
    qDebug() << handle << " " << oTcpSocket->socketDescriptor();
    socList.push_back(oTcpSocket);
    connect(oTcpSocket, &TcpSocket::emit_disConnected, [this](int isocketDescriptor){
        for(auto it=TcpSocket::tcpTree.begin();it!=TcpSocket::tcpTree.end();it++){
            if(it.value()->socketDescriptor()==isocketDescriptor){
                TcpSocket::tcpTree.erase(it);
                break;
            }
        }

        for(int index = 0; index < socList.size(); ++index)
        {
            QTcpSocket *item = socList.at(index);
            if(item->socketDescriptor() == isocketDescriptor)
            {
                item->deleteLater();
                socList.removeAt(index);
            }
        }

    });
}

void testTcpSocketServer()
{
    TcpSocketServer* m_pTcpServer = new TcpSocketServer();
    if (!m_pTcpServer->listen(QHostAddress::Any, 8888))
    {
        qDebug() << "m_pTcpServer->listen() error";
    }
}

void ServerResponseThread::run()
{
    while(1)
    {
        processObject response=processObject();
        QString userid;
        QString content;
        if(dbProcess::correspondQueue.size()!=0)
        {
            response=dbProcess::correspondQueue.front();
            dbProcess::correspondQueue.pop();

            emit db_response_signal(response);
        }
    }
}

